package com.study.ws.config.ws.interceptor;

import jakarta.servlet.http.HttpSession;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.lang.NonNull;
import org.springframework.util.ObjectUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * ws 授权拦截器
 *
 * @author xl-9527
 * @since 2025/3/25
 **/
public class AuthHandshakeInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(@NonNull final ServerHttpRequest request, @NonNull final ServerHttpResponse response, @NonNull final WebSocketHandler wsHandler, @NonNull final Map<String, Object> attributes) throws Exception {
        HttpSession session = ((ServletServerHttpRequest) request).getServletRequest().getSession();
        if (session == null) {
            return false;
        } else {
            String[] paths = request.getURI().getPath().split("/");
            if (!ObjectUtils.isEmpty(paths)) {
                attributes.put("userId", paths[paths.length - 1]);
            }
        }
        return true;
    }

    @Override
    public void afterHandshake(@NonNull final ServerHttpRequest request, @NonNull final ServerHttpResponse response, @NonNull final WebSocketHandler wsHandler, final Exception exception) {

    }
}
